package com.zzh.partnersys.controller;


import cn.hutool.core.collection.CollUtil;
import com.zzh.partnersys.common.exception.ResultUtils;
import com.zzh.partnersys.constant.TagConstant;
import com.zzh.partnersys.entity.vo.TagGroupVO;
import com.zzh.partnersys.entity.vo.TagSearchVO;
import com.zzh.partnersys.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 标签管理Controller
 * </p>
 *
 * @author zzh
 * @since 2024-07-13
 */
@RestController
@RequestMapping("/tag")
public class TagController {

    @Autowired
    private TagService tagService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取所有标签和分类
     * @return
     */
    @GetMapping("/allTags")
    public ResultUtils<List<TagGroupVO>> getAllTagAndCategory(){
        //从缓存中获取
        ValueOperations<String,Object> valueOperations = redisTemplate.opsForValue();
        List<TagGroupVO> list = (List<TagGroupVO>) valueOperations.get(TagConstant.TAG_ALL_KEY_SELECT);
        if (CollUtil.isNotEmpty(list)){
            return ResultUtils.ok(list);
        }
        //从数据库中获取
        //{id,name,List<TagDO>} TagVo={id,name,isSelect=false}
        List<TagGroupVO> tagGroupVOList = tagService.selectAllTagsAndCategory();
        if (tagGroupVOList != null){
            valueOperations.set(TagConstant.TAG_ALL_KEY_SELECT,tagGroupVOList,3,TimeUnit.DAYS);
        }

        return ResultUtils.ok(tagGroupVOList);
    }

    /**
     * ��ѯ�����еķ���+�����µı�ǩ�������仺��
     * (Ϊ���û����ݱ�ǩ��ѯ�û�)
     * @return
     */
    @GetMapping("/allTagsToSearchUser")
    public ResultUtils getAllTagAndCategoryToSearch(){
        //���ȿ���ȥ�жϱ��ػ���Map���Ƿ��??

        //����ж�redis�Ƿ񻺴�??
        ValueOperations<String,Object> valueOperations = redisTemplate.opsForValue();
        List<TagSearchVO> list = (List<TagSearchVO>) valueOperations.get(TagConstant.TAG_ALL_KEY_SEARCH);
        if (list != null){
            return ResultUtils.ok(list);
        }
        //�����ȥ��ѯ���ݿ�+����
        //{id,name,List<TagDO>} TagVo={id,name,isSelect=false}
        List<TagSearchVO> tagGroupVOList = tagService.selectAllTagsToSearchUser();
        valueOperations.set(TagConstant.TAG_ALL_KEY_SEARCH,tagGroupVOList,3, TimeUnit.DAYS);

        return ResultUtils.ok(tagGroupVOList);
    }

}

